package com.yxch.admin.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import static com.yxch.admin.utils.CommenEnum.*;


@Slf4j
public class Upload {
    public static String upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String suffix = filename.substring(index);
        String newname = UUID.randomUUID().toString() + suffix;
        log.info("新文件名" + newname);
        File newfile = new File(UPLOAD_DIR.getContent() + newname);
        try {
            file.transferTo(newfile);
            log.info("已连接服务器图形库" + UPLOAD_DIR.getContent() + newname);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("未连接服务器暂时不能使用，以默认url替代");
        }
        if (newfile.exists()) {
            return NGINX_HTTP.getContent() + newname;
        }
        return DEFAULT_SEMCOVER.getContent();
    }

    public static String upload(MultipartFile file, String path) {
        //path:如video_cover/.....
        String filename = file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String suffix = filename.substring(index);
        String newname = UUID.randomUUID().toString() + suffix;
        log.info("新文件名" + newname);
        File newfile = new File(UPLOAD_DIR.getContent() + path + newname);
        try {
            file.transferTo(newfile);
            log.info("已连接服务器图形库" + UPLOAD_DIR.getContent() + path + newname);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("未连接服务器暂时不能使用，以默认url替代");
        }
        if (newfile.exists()) {
            return NGINX_HTTP.getContent() + path + newname;
        }
        return DEFAULT_SEMCOVER.getContent();
    }
}
